import axios, { CreateAxiosDefaults, Method } from "axios";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";

const baseURL = import.meta.env.VITE_BASE_URL

const config:  CreateAxiosDefaults = {
  baseURL, 
  timeout: 10000,
  withCredentials: true
}
const instance = axios.create(config)

instance.interceptors.request.use(
  (request) => {
    const token = localStorage.getItem('token')
    if(token){
      request.headers.token = token
    }
    return request
  },
  (err) => Promise.reject(err)
)

instance.interceptors.response.use(
  res => {
    if(res.data.code === '2000'){
      return res.data
    }
    return Promise.reject(res.data)
  },
  err => {
    if(err.response.status === 401){
      const router = useRouter()
      ElMessage.error("登录超时，请重新登录")
      router.push({
        path: "/login",
        query:{
          redirect: router.currentRoute.value.fullPath
        }
      })
    }
    return Promise.reject(err)
  }
)

export type Data<T> = {
  code: string
  message: string
  data: T
}

export type RequestParam = {
  url: string
  method: Method
  params?: object,
  data?: object
}

const requets = <T>({ url, method, params, data }: RequestParam) => instance.request<T, Data<T>>({
  url,
  method,
  params: params ?? null,
  data: data ?? null
})

export { baseURL, instance, requets };
